package com.zhe.zheblogmaster.handler.admin;

import com.github.pagehelper.PageInfo;
import com.zhe.zheblogmaster.config.BlogConstants;
import com.zhe.zheblogmaster.entity.Blog;
import com.zhe.zheblogmaster.entity.BlogCategory;
import com.zhe.zheblogmaster.service.BlogCategoryService;
import com.zhe.zheblogmaster.service.BlogService;
import com.zhe.zheblogmaster.util.ResultBody;
import com.zhe.zheblogmaster.util.ZheBlogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author WHAOU
 * @date 2021/9/8
 * @email whaou@qq.com
 */
@ResponseBody
@Controller
@RequestMapping("/admin/blog")
public class BlogHandler {
    @Autowired
    private BlogCategoryService categoryService;
    @Autowired
    private BlogService blogService;

    /**
     * editormd本地上传图片
     * 由于editormd响应码与自定义响应码不同
     * {
     * success:0|1  0表示上传失败，1表示长传成功
     * message:"提示信息"
     * url:"图片访问地址，上传成功时才返回"
     * }
     * 不能之间返回，采用response返回
     *
     * @param img 图片
     */
    @PostMapping("/md/upload")
    public void uploadImg(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam("editormd-image-file") MultipartFile img) throws IOException {
        // 获取图片文件的原始名称
        String originalFilename = img.getOriginalFilename();
        // 获取文件后缀
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成图片文件名称
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random random = new Random();
        String newFileName = formater.format(ZheBlogUtils.getNow()) + "_" + random.nextInt(100) + suffixName;
        // 生成目标文件
        File destFile = new File(BlogConstants.ROOT + BlogConstants.FILE_UPLOAD_DIC + newFileName);
        // JSONObject json = new JSONObject();
        try {
            // 生成图片访问路径
            String imgUrl = ZheBlogUtils.getHost(new URI(request.getRequestURI())).toString() + BlogConstants.MD_IMAGE_URL + newFileName;
            // 创建文件夹
            File directory = new File(BlogConstants.ROOT + BlogConstants.FILE_UPLOAD_DIC);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    throw new IOException("文件夹创建失败：" + directory);
                }
            }
            img.transferTo(destFile);
            response.setHeader("Content-Type", "text/html");
            response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + imgUrl + "\"}");
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\":0}");
        }
    }

    /**
     * 更新博客
     *
     * @param blogId         博客id
     * @param blogTitle      博客标题
     * @param blogCategoryId 博客分类id
     * @param blogContent    博客内容
     * @param blogStatus     博客状态
     * @param enableComment  是否允许评论
     * @return 更新成功则返回“修改成功”，否则返回错误提示
     */
    @PostMapping("/update")
    public ResultBody<String> updateBlog(@RequestParam("blogId") Long blogId,
                                         @RequestParam("blogTitle") String blogTitle,
                                         @RequestParam("blogCategoryId") Integer blogCategoryId,
                                         @RequestParam("blogContent") String blogContent,
                                         @RequestParam("blogStatus") Byte blogStatus,
                                         @RequestParam("enableComment") Byte enableComment) {
        if (!StringUtils.hasLength(blogTitle)) {
            return ResultBody.error("博客标题不能为空");
        }
        if (blogTitle.trim().length() > 150) {
            return ResultBody.error("标题过长");
        }
        if (!StringUtils.hasLength(blogContent)) {
            return ResultBody.error("博客内容不能为空");
        }
        Blog blog = new Blog();
        blog.setBlogId(blogId);
        blog.setBlogTitle(blogTitle);
        blog.setBlogCategoryId(blogCategoryId);
        blog.setBlogContent(blogContent);
        blog.setBlogStatus(blogStatus);
        blog.setEnableComment(enableComment);
        String msg = blogService.updateBlog(blog);
        if (BlogConstants.FEEDBACK_SUCCESS.equals(msg)) {
            return ResultBody.successWithData("修改成功");
        } else {
            return ResultBody.error(msg);
        }
    }


    /**
     * 根据博客id删除博客
     *
     * @param ids 博客id
     */
    @PostMapping("/delete")
    public ResultBody<String> deleteBlogs(@RequestBody Long[] ids) {
        if (ids == null || ids.length < 1) {
            return ResultBody.error("请选择要删除的博客id");
        }
        int count = blogService.removeBlogsByIds(ids);
        if (count > 0) {
            return ResultBody.successWithData(String.valueOf(count));
        } else {
            return ResultBody.error("删除失败");
        }
    }


    /**
     * 编辑指定id的博客
     */
    @GetMapping("edit/{blogId}")
    public ResultBody<Map<String, Object>> editBlog(@PathVariable("blogId") Long blogId) {
        Map<String, Object> data = new HashMap<>(2);
        List<BlogCategory> categories = categoryService.getAll();
        data.put("categories", categories);
        Blog blog = blogService.getBlogById(blogId);
        data.put("blog", blog);
        return ResultBody.successWithData(data);
    }

    /**
     * 获取当前页所有博客列表
     *
     * @param pageNum 当前页
     */
    @RequestMapping("/list")
    public ResultBody<PageInfo<Blog>> getBlogList(@RequestParam("pageNum") Integer pageNum,
                                                  @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> param = null;
        if (StringUtils.hasLength(keyword)) {
            param = new HashMap<>(1);
            param.put("keyword", keyword);
        }
        PageInfo<Blog> blogPage = blogService.getBlogsByMap(pageNum, param);
        return ResultBody.successWithData(blogPage);
    }

    /**
     * 保存博客
     *
     * @param title         博客标题
     * @param categoryId    博客分类id
     * @param content       博客内容
     * @param status        博客状态
     * @param enableComment 是否允许评论
     * @return 保存成功则返回空数据，失败则返回错误原因
     */
    @PostMapping("/save")
    public ResultBody<String> saveBlog(@RequestParam("blogTitle") String title,
                                       @RequestParam("blogCategoryId") Integer categoryId,
                                       @RequestParam("blogContent") String content,
                                       @RequestParam("blogStatus") Byte status,
                                       @RequestParam("enableComment") Byte enableComment) {
        if (title == null || "".equals(title)) {
            return ResultBody.error("博客标题不能为空！");
        }
        if (title.length() > 200) {
            return ResultBody.error("博客标题不能超过200字符！");
        }
        if (content == null || "".equals(content)) {
            return ResultBody.error("博客内容不能为空！");
        }
        if (content.length() > 100000) {
            return ResultBody.error("博客内容过长！");
        }

        Blog blog = new Blog();
        blog.setBlogTitle(title);
        blog.setBlogCategoryId(categoryId);
        blog.setBlogContent(content);
        blog.setBlogStatus(status);
        blog.setEnableComment(enableComment);
        blog.setCreateTime(ZheBlogUtils.getNow());
        Boolean result = blogService.saveBlog(blog);
        if (result) {
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("保存失败！");
        }
    }

    /**
     * 返回新增博客页面所需数据
     */
    @GetMapping("/new")
    public ResultBody<List<BlogCategory>> newBlog() {
        List<BlogCategory> categoryList = categoryService.getAll();
        return ResultBody.successWithData(categoryList);
    }
}
